from django.views.decorators.csrf import csrf_exempt
from ..utils.response import success_response, error_response
from datetime import datetime, timedelta
import os
from django.conf import settings
from django.utils import timezone
from django.db.models import Q
from api.models.audio import Audio
from api.models.wechat_user import WechatUser

@csrf_exempt
def cleanup_audio_files(request):
    """
    清理音频文件的API接口
    仅管理员可访问
    """
    try:
        # 使用timezone.now()获取带时区的当前时间
        one_week_ago = timezone.now() - timedelta(days=7)
        print(f"一周前的日期: {one_week_ago}")
        
        # 从wechat_user表获取所有用户ID
        user_ids = WechatUser.objects.values_list('id', flat=True)
        print(f"用户ID: {user_ids}")
        
        for user_id in user_ids:
            # 获取用户一周内的所有音频记录，按创建时间降序排序
            recent_audio_records = Audio.objects.filter(
                user_id=user_id,
                created_at__gte=one_week_ago
            ).order_by('-created_at')
            print(f"用户 {user_id} 一周内的记录: {recent_audio_records}")
            # 如果一周内的记录数超过10，删除多余的记录
            if recent_audio_records.count() > 50:
                records_to_delete = recent_audio_records[50:]
                print(f"用户 {user_id} 一周内有 {recent_audio_records.count()} 条记录，需要删除 {len(records_to_delete)} 条")
                
                for record in records_to_delete:
                    try:
                        # 删除文件
                        file_path = os.path.join(settings.MEDIA_ROOT, record.url)
                        print(f"删除文件: {file_path}")
                        if os.path.exists(file_path):
                            os.remove(file_path)
                            print(f"成功删除文件: {file_path}")
                        else:
                            print(f"文件不存在: {file_path}")
                            
                        # 删除数据库记录
                        record.delete()
                        print(f"成功删除记录: {record.id}")
                    except Exception as e:
                        print(f"删除记录 {record.id} 时发生错误: {str(e)}")
                        continue
            
            # 删除一周前的记录
            old_records = Audio.objects.filter(
                Q(user_id=user_id) & Q(created_at__lt=one_week_ago)
            )
            
            if old_records.exists():
                print(f"用户 {user_id} 有一周前的记录 {old_records.count()} 条需要删除")
                
            for record in old_records:
                try:
                    # 删除文件
                    file_path = os.path.join(settings.MEDIA_ROOT, record.url)
                    if os.path.exists(file_path):
                        os.remove(file_path)
                        print(f"成功删除一周前的文件: {file_path}")
                    else:
                        print(f"一周前的文件不存在: {file_path}")
                        
                    # 删除数据库记录
                    record.delete()
                    print(f"成功删除一周前的记录: {record.id}")
                except Exception as e:
                    print(f"删除一周前的记录 {record.id} 时发生错误: {str(e)}")
                    continue
        
        print("音频文件清理完成")
        return success_response({
            'message': '音频文件清理完成',
            'code': 200
        })
    except Exception as e:
        return error_response(f'清理音频文件时发生错误: {str(e)}') 